import Taro from '@tarojs/taro';
import { View, Image, Input, Block } from '@tarojs/components';
import './index.scss'
import http from '@/utils/http';
import utils from '@/utils/util'
import UseRecordItem from '@/components/useRecordItem/index';
import { get as getGlobalData } from '@/global'
import StatusPages from '@/components/statusPages/index';
import MoreFooter from '@/components/moreFooter/index';

let app = Taro.getApp();
export default class ConsumptionRecord extends Taro.Component {
    constructor() {
        super();
        this.state = {
            isChang: false,
            isOpen: false,
            semonth: {
                name: '当天',
                value: 1
            },
            setyps: 1,
            selected: '',
            pageNumber: 1,
            moreType: 'none',
            statusType: 'none', // none 不显示空白页  empty //显示空白页
            statuserro: false, // 是否显示错误页
            isfocus: false,
            consumptionLiest: [],
            keyword: '',
            month: [{
                name: '当天',
                value: 1
            }, {
                name: '本月',
                value: 2
            }, {
                name: '最近三月',
                value: 3
            }, {
                name: '最近半年',
                value: 4
            }],
            types: [{
                name: '不限',
                value: 1
            }, {
                name: '使用',
                value: 2
            }, {
                name: '回收',
                value: 3
            }]
        }
    }
    config = {
        navigationBarTitleText: '消耗记录'
    }
    tapMask() {
        this.setState({
            isChang: false,
            isOpen: false
        })
    }
    componentDidShow() {
        this.getDrugUseLogs();
    }
    choseType(e) {
        console.log(e)
        const { selected, isOpen } = this.state;
        if (selected !== e.target.dataset.value) {
            this.setState({
                selected: e.target.dataset.value,
                isChang: true,
                isOpen: true
            })
        } else if (isOpen === false) {
            this.setState({
                isChang: true,
                isOpen: true
            })
        } else {
            this.setState({
                isChang: false,
                isOpen: false
            })
        }
    }
    refresh() { //下拉刷新
        var {
            moreType
        } = this.state;
        if (moreType != "loading") {
            this.setState({
                pageNumber: 1,
                moreType: 'none'
            }, () => {
                this.getDrugUseLogs();
            })
        }
    }
    onPullDownRefresh() {
        this.refresh();
    }
    onReachBottom() { //滚动触底加载
        let {
            moreType,
            pageNumber,
        } = this.state;
        if (moreType == "showText") {
            pageNumber = pageNumber + 1;
            this.setState({
                pageNumber,
                moreType: "loading"
            }, () => {
                this.getDrugUseLogs();
            });
        }
    }
    getDrugUseLogs() {
        let drugid = app.getValueSync('lastwardId');
        let { keyword: ypin, pageNumber, semonth, consumptionLiest, moreType } = this.state;
        let userInfo = getGlobalData('userInfo') || utils.getUserInfo();
        http.get('getDrugUseLogs', {
            drugid,
            loginid: userInfo.loginid,
            ypin,
            dates: semonth.value,
            pageNumber,
            pagesize: 10
        }).then((res) => {
            console.log(res);
            Taro.stopPullDownRefresh();
            let list = res.datas.pageRes || [];
            list.map((item) => {
                item.timesString = this.timesFun(item.usetime.replace(/-/g, "/"))
            })
            moreType = "showText";
            list.length < 10 ? moreType = "noMore" : moreType;
            if (pageNumber != 1) {
                list = consumptionLiest.concat(list);
            }
            this.setState({
                moreType,
                statusType: list.length > 0 ? 'none' : 'empty',
                statuserro: false,
                consumptionLiest: list
            });
        }).catch((e) => {
            console.log(e);
            Taro.stopPullDownRefresh();
            this.setState({
                moreType: consumptionLiest.length > 0 ? 'error' : 'none',
                statusType: consumptionLiest.length > 0 ? 'none' : 'empty',
                statuserro: consumptionLiest.length > 0 ? false : true,
            })
        })
    }
    timesFun(timesData) {
        var dateBegin = new Date(timesData);
        var dateEnd = new Date(); //获取当前时间
        var dateDiff = dateEnd.getTime() - dateBegin.getTime(); //时间差的毫秒数
        var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
        var leave1 = dateDiff % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
        var hours = Math.floor(leave1 / (3600 * 1000)) //计算出小时数
        //计算相差分钟数
        var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
        var minutes = Math.floor(leave2 / (60 * 1000)) //计算相差分钟数
        //计算相差秒数
        var timesString = '';

        if (dayDiff != 0) {
            timesString = timesData.substring(0, timesData.length - 3);
        } else if (dayDiff == 0 && hours != 0) {
            var current_times = timesData.split(' ')[1].substring(0, 5);
            timesString = (dateEnd.getHours() < hours ? '昨天' : '今天') + current_times;
        } else if (dayDiff == 0 && hours == 0) {
            timesString = '刚刚';
            if (minutes) {
                timesString = minutes + '分钟之前';
            }
        }
        return timesString
    }
    tapDetails(e, item) {
        Object.keys(item).map((items) => {
            item[items] = encodeURIComponent(item[items])
        })
        Taro.navigateTo({
            url: '/pages/consumptionRecord/recordDetails/index?' + utils.queryconcat(item)
        })
    }
    inputChang(e) {
        this.setState({
            keyword: e.detail.value.replace(/\s+/g, '')
        })
    }
    inputConfirm() {
        this.refresh();
    }
    render() {
        const { isChang, month, types, semonth, selected, setyps, isOpen, consumptionLiest, isfocus, keyword, statuserro, statusType, moreType, pageNumber } = this.state;
        return (
            <View className='consumption-record'>
                <View className='conditions-box'>
                    <View className='search-box box_s mt-auto pt-1-5 pr-3-5 pl-3-5 pb-1-5 bg_fff'>
                        {isfocus || keyword ? <Input className='input-class pl-3-5 box_s' value={keyword} onBlur={() => { this.setState({ isfocus: false }) }} onChange={(e) => { this.inputChang(e) }} confirm-type='搜索' placeholder='药品名称/批号' focus onConfirm={(e) => { this.inputConfirm() }}></Input> :
                            <View onClick={() => { this.setState({ isfocus: true }) }} className='search-center pl-4-5 pr-3-5 flex flex-r flex-item-between flex-item-v-center box_s'>
                                <View className='fc_B9C ft24'>药品名称/批号</View>
                                <Image style={{ width: Taro.pxTransform(42), height: Taro.pxTransform(42) }} src={require('../../assets/imgs/consumption/syjl_icon_search.png')}></Image>
                            </View>
                        }
                    </View>
                    <View className='mt-2-5 conditions  flex flex-c flex-warp  bg_fff ov_h' style={{ height: isOpen ? Taro.pxTransform(215) : Taro.pxTransform(88) }}>
                        <View className='types flex line-b'>
                            <View className='flex-1 flex flex-item-center' >
                                <View data-value='month' className={`default-css ${selected === 'month' && isOpen ? 'on' : ''}`} onClick={(e) => { this.choseType(e) }}>
                                    {semonth.name}
                                </View>
                            </View>
                            {/* <View className='flex-1 flex flex-item-center'>
                                <View data-value='type' className={`default-css ${selected === 'type' ? 'on' : ''}`} onClick={(e) => { this.choseType(e) }}>
                                    类型
                                </View>
                            </View> */}
                        </View>
                        {
                            selected === 'month' ?
                                <View className='month pl-2-5 pr-2-5 flex fle-r flex-item-between flex-item-v-center' >
                                    {
                                        month.map((item) => {
                                            return (
                                                <View key={item.value} onClick={() => {
                                                    this.setState({
                                                        semonth: item,
                                                        isChang: false,
                                                        isOpen: false
                                                    }, () => { this.refresh() })
                                                }} className={`btn-item  ft24 box_s ${semonth.value === item.value ? 'on' : ''}`}
                                                >
                                                    {item.name}
                                                </View>
                                            )
                                        })
                                    }
                                </View> :
                                <View className='month pl-2-5 pr-2-5 flex fle-r flex-item-between flex-item-v-center' >
                                    {
                                        types.map((item) => {
                                            return (
                                                <View key={item.value} onClick={() => {
                                                    this.setState({
                                                        setyps: item.value,
                                                        isChang: false,
                                                        isOpen: false
                                                    }, () => { this.refresh() })
                                                }} className={`btn-item  ft24 box_s ${setyps === item.value ? 'on' : ''}`}
                                                >
                                                    {item.name}
                                                </View>
                                            )
                                        })
                                    }
                                </View>
                        }
                    </View>
                </View>
                {isChang ? <View className='mask-box' onClick={() => { this.tapMask() }} onTouchMove={(e) => { e.stopPropagation() }}></View> : null}
                <Block>
                    {consumptionLiest.length && <View>
                        {
                            consumptionLiest.map((item) => {
                                return (
                                    <View key={item} className='pl-2-5 pr-2-5' >
                                        <UseRecordItem RecordItem={item} itemTap={(e, obj) => {
                                            this.tapDetails(e, obj)
                                        }}
                                        ></UseRecordItem>
                                    </View>
                                )
                            })
                        }
                        <MoreFooter moreType={moreType} restloading={() => { this.setState({ pageNumber: pageNumber > 1 ? pageNumber - 1 : 1 }, () => { this.getDrugUseLogs() }) }} ></MoreFooter>
                    </View>}
                </Block>
                <StatusPages mt='mt-20'
                  refresh={() => { this.refresh() }}
                  statusType={statusType}
                  statuserro={statuserro}
                  isVh100={consumptionLiest.length < 0 && statuserro ? true : false}
                ></StatusPages>
            </View>
        )
    }
}

